﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Newtonsoft.Json;
using WorkflowCore2210A.Application.Dto.Output;
using DevExpress.XtraRichEdit.API.Native;
using RBAC_Application.Dto.Output;
using System.Net.Http;
using WorkflowCore2210A.Application.Dto;
using B.MESUI.Login.EquipmentManagement.DTO;
using Microsoft.Win32;
using System.IO;

namespace B.MESUI.Login.WorkflowCore.Instance
{
    public partial class GetAllInstance : DevExpress.XtraEditors.XtraForm
    {
        private Label lblTitle;
        private Label lblApplicant;
        private Label lblStatus;
        private DataGridView dgvAudit;
        private DataGridView dgvForm;

        // 字段定义
        private Label lblReason;
        private Label lblDays;
        private ListView lvAudit;

        private List<Label> formLabels = new List<Label>();
        private int formLabelStartTop = 0; // 记录动态Label的起始位置

        public GetAllInstance(string workflowId)
        {
            InitializeComponent();
            this.CenterToParent();
            // 初始化控件
            lblTitle = new Label() { Left = 20, Top = 20, Width = 400 };
            lblApplicant = new Label() { Left = 20, Top = 50, Width = 400 };
            lblStatus = new Label() { Left = 20, Top = 80, Width = 400 };

            dgvAudit = new DataGridView() { Left = 20, Top = 120, Width = 600, Height = 150, ReadOnly = true, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill };
            dgvForm = new DataGridView() { Left = 20, Top = 290, Width = 600, Height = 150, ReadOnly = true, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill };

            // 审批流程ListView
            lvAudit = new ListView()
            {
                Left = 20,
                Top = 120,
                Width = 700,
                Height = 100, // 你可以根据实际内容调整
                View = View.Details,
                FullRowSelect = true,
                GridLines = true,
                Font = new Font("微软雅黑", 11)
            };
            lvAudit.Columns.Add("审批人", 80);
            lvAudit.Columns.Add("步骤", 80);
            lvAudit.Columns.Add("状态", 80);
            lvAudit.Columns.Add("创建时间", 300);
            this.Controls.Add(lvAudit);

            // 动态设置Label的Top
            int labelStartTop = lvAudit.Top + lvAudit.Height + 20; // 20为间隔
            lblReason = new Label() { Left = 20,Height=40, Top = labelStartTop, Width = 400, Font = new Font("微软雅黑", 12) };
            lblDays = new Label() { Left = 20, Height=40, Top = labelStartTop + 40, Width = 400, Font = new Font("微软雅黑", 12) };
            this.Controls.Add(lblReason);
            this.Controls.Add(lblDays);

            // 在类中添加
            // 在构造函数里，初始化一个Panel用于放表单字段
            Panel panelFormFields = new Panel() { Left = 20, Top = lvAudit.Top + lvAudit.Height + 20, Width = 600, AutoScroll = true };
            this.Controls.Add(panelFormFields);

            this.Controls.Add(lblTitle);
            this.Controls.Add(lblApplicant);
            this.Controls.Add(lblStatus);
            this.Controls.Add(lvAudit);
            this.Controls.Add(lblReason);
            this.Controls.Add(lblDays);

            // 只异步获取数据
            LoadDetailAsync(workflowId);
        }

        private async void LoadDetailAsync(string workflowId)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    // 这里请替换为你的实际接口地址
                    string url = $"{BaseUrl.WorkflowUrl}Workflow/GetWorkflowDetail?workflowId={workflowId}";
                    var response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    var json = await response.Content.ReadAsStringAsync();

                    // 假设返回格式为 { code: 200, data: {...} }
                    var result = JsonConvert.DeserializeObject<WorkflowCore2210A.Application.Dto.ApiPaging<WorkflowInstalceDetailOutput>>(json);
                    if (result != null && result.Code == 200)
                    {
                        BindDetail(result.Data);
                    }
                    else
                    {
                        MessageBox.Show("获取详情失败！");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请求异常：" + ex.Message);
            }
        }

        private void BindDetail(WorkflowInstalceDetailOutput detail)
        {
            // 实例详情
            lblTitle.Text = $"标题：{detail.WorkflowInstance.Title}";
            lblApplicant.Text = $"申请人：{detail.WorkflowInstance.ApplicantUserName}";
            lblStatus.Text = $"状态：{detail.WorkflowInstance.Status}";

            // 审批进度
            lvAudit.Items.Clear();
            if (detail.AuditList != null)
            {
                foreach (var item in detail.AuditList)
                {
                    string statusText = item.Status ? "已审批" : "未审批";
                    string updateTime = item.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    var lvi = new ListViewItem(new string[]
                    {
                        item.AuditUserName,
                        item.StepName,
                        statusText,
                        updateTime
                    });
                    lvAudit.Items.Add(lvi);
                }
            }

            // 表单数据
            Panel panelFormFields = this.Controls.OfType<Panel>().FirstOrDefault(p => p.Left == 20 && p.Top == lvAudit.Top + lvAudit.Height + 20);
            if (panelFormFields != null)
            {
                panelFormFields.Controls.Clear();
                formLabels.Clear();
                if (!string.IsNullOrEmpty(detail.FormData))
                {
                    var formFields = JsonConvert.DeserializeObject<List<WorkflowCore2210A.Application.Dto.FormField>>(detail.FormData);
                    int curTop = 0;
                    foreach (var field in formFields)
                    {
                        var lbl = new Label()
                        {
                            Left = 0,
                            Top = curTop,
                            Width = 400,
                            Height = 32,
                            Font = new Font("微软雅黑", 12),
                            Text = $"{field.DisplayFieldName}：{field.DisplayValue}"
                        };
                        panelFormFields.Controls.Add(lbl);
                        formLabels.Add(lbl);
                        curTop += 36;
                    }
                }
            }
        }
    }

 
}